/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package manager.modulo.ordemservico.fonte;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.logging.Level;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.table.TableRowSorter;
import manager.auxiliares.*;
import manager.helpers.table.TableModel;
import manager.helpers.table.TableRender;
import manager.helpers.table.TableRowComparator;
import manager.helpers.validation.ComboBoxValidator;
import manager.helpers.validation.TextFieldValidator;
import manager.helpers.validation.ValidationFunctions;
import manager.interfaces.InterfaceTable;
import manager.modulo.ordemservico.dao.*;
import manager.modulo.ordemservico.enumerator.EnumSituacaoOrdemServico;
import manager.modulo.ordemservico.enumerator.EnumSituacaoOrdemServico.SituacaoOS;
import manager.modulo.ordemservico.enumerator.EnumTipoOrdemServico.TipoOS;
import manager.modulo.sistema.dao.UsuarioDao;
import manager.principal.fonte.JanelaLogin;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.view.JasperViewer;

/**
 *
 * @author THIAGO
 */
public class JanelaOrdemServico extends javax.swing.JFrame {

    int idOrdemServico = 0;
    TableModel tableModel;
    TableRender tableRender;
    TableRowSorter tableRowSorter;
    LinkedList<SituacaoOrdemServicoDao> listaSituacao;

    /**
     * Creates new form JanelaOrdemServico
     */
    public JanelaOrdemServico() {
        initComponents();
    }

    /**
     * Creates new form UserWindow
     */
    public JanelaOrdemServico(int novoIdOrdemServico) {
        try {
            // Define layout de acordo com o SO que estiver rodando
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            this.setIconImage(JanelaLogin.icon);
            initComponents();
            idOrdemServico = novoIdOrdemServico;
            configureWindow();
            this.setLocationRelativeTo(null);
            this.setVisible(true);
        } catch (Exception e) {
            MensagemExcessao.mostrarMensagem(e, this.getTitle());
        }
    }

    private void setEntityInformations() {
        jButton2.setText("Editar");
        jButton2.setIcon(new Icons().getEdit());

        OrdemServicoDao ordemServicoDao = new OrdemServicoDao();
        ordemServicoDao.buscar(idOrdemServico);

        jTextArea1.setText(ordemServicoDao.getMaterialUtilizado());
        jTextArea2.setText(ordemServicoDao.getDificuldades());

        if (ordemServicoDao.isAvaliada()) {
            jCheckBox2.setSelected(true);
        }

        PontoAtendimentoDao pontoAtendimentoDao = new PontoAtendimentoDao();
        pontoAtendimentoDao.buscar(ordemServicoDao.getIdPontoAtendimento());

        UnidadeAtendimentoDao unidadeAtendimentoDao = new UnidadeAtendimentoDao();
        unidadeAtendimentoDao.buscar(pontoAtendimentoDao.getIdUnidadeAtendimento());

        jComboBox1.removeAllItems();
        jComboBox1.addItem(unidadeAtendimentoDao.getIdentificador());
        jComboBox1.setEnabled(false);

        jComboBox2.removeAllItems();
        jComboBox2.addItem(pontoAtendimentoDao.getIdentificador());
        jComboBox2.setEnabled(false);

        ProcedimentoDao procedimentoDao = new ProcedimentoDao();
        procedimentoDao.buscar(ordemServicoDao.getIdProcedimento());

        jComboBox3.setSelectedItem(procedimentoDao.getNome());
        jComboBox3.setEnabled(false);

        jTextField1.setText(ordemServicoDao.getProblemaInformado());
        jTextField1.setEnabled(false);

        SituacaoOrdemServicoDao situacaoOrdemServicoDao = new SituacaoOrdemServicoDao();
        situacaoOrdemServicoDao.buscar(SituacaoOrdemServicoDao.buscarUltimaSituacao(idOrdemServico));

        jTextField3.setText(Format.formatTimeStampToCompleteDatetime(situacaoOrdemServicoDao.getModificacao()));
        jTextField5.setText(EnumSituacaoOrdemServico.ConvertEnumString(situacaoOrdemServicoDao.getSituacao()));

        UsuarioDao usuarioDao = new UsuarioDao();
        usuarioDao.buscar(situacaoOrdemServicoDao.getIdUsuario());

        jTextField4.setText(usuarioDao.getEmail());

        if (ordemServicoDao.isFinalizada()) {
            desabilitarCampos();
            jButton2.setEnabled(false);
        }
        // searchTable();
    }

    /**
     * Inicializando as configurações da tela
     *
     * @throws SQLException
     */
    private void configureWindow() throws SQLException {
        //Carregando unidades
        LinkedList<String> listaUnidadeAtendimento = new UnidadeAtendimentoDao().buscar("Identificador da Unid. Atend.", "%", false);
        for (int i = 0; i < listaUnidadeAtendimento.size(); i++) {
            jComboBox1.addItem(listaUnidadeAtendimento.get(i));
        }

        //Carregando Procedimentos
        LinkedList<String> listaProcedimentos = new ProcedimentoDao().buscar("Nome do Procedimento", "%", false);
        for (int i = 0; i < listaProcedimentos.size(); i++) {
            jComboBox3.addItem(listaProcedimentos.get(i));
        }

        //Carregando Situações
        LinkedList<SituacaoOS> listaSituacaoOS = EnumSituacaoOrdemServico.ListaSituacao();
        jComboBox4.addItem("SELEICONE UMA SITUAÇÃO");

        for (int i = 0; i < listaSituacaoOS.size(); i++) {
            jComboBox4.addItem(EnumSituacaoOrdemServico.ConvertEnumString(listaSituacaoOS.get(i)));
        }
        if (idOrdemServico != 0) { // Edição de usuário
            listaSituacao = SituacaoOrdemServicoDao.buscaListaSituacao(idOrdemServico);

            setEntityInformations();
        } else {
            listaSituacao = new LinkedList<SituacaoOrdemServicoDao>();

            desabilitarCampos();


            jTextField5.setText(EnumSituacaoOrdemServico.ConvertEnumString(SituacaoOS.EMABERTO));
            jTextField3.setText(Format.formatTimeStampToCompleteDatetime(DateConverter.getDataAtualBancoDados()));


            jTextField3.setText(Format.formatTimeStampToCompleteDatetime(DateConverter.getDataAtualBancoDados()));
            jTextField5.setText(EnumSituacaoOrdemServico.ConvertEnumString(SituacaoOS.EMABERTO));
            jTextField4.setText(JanelaLogin.getUsuario().getNome());

        }

        configurarTabela();
        verificarCampoObrigatorios();
    }

    private void desabilitarCampos() {
        jTextArea1.setEnabled(false);
        jTextArea2.setEnabled(false);
        jComboBox4.setEnabled(false);
        jTextArea3.setEnabled(false);
        jButton4.setEnabled(false);
    }

    private LinkedList<String> validarCamposOrdemServico() {
        LinkedList<String> fieldList = new LinkedList<String>();
        if (!((TextFieldValidator) jTextField1).validarCampo()) {
            fieldList.add(((TextFieldValidator) jTextField1).getjLabel().getText());
        }
        if (!((ComboBoxValidator) jComboBox1).validarCampo()) {
            fieldList.add(((ComboBoxValidator) jComboBox1).getJLabel().getText());
        }
        if (!((ComboBoxValidator) jComboBox2).validarCampo()) {
            fieldList.add(((ComboBoxValidator) jComboBox2).getJLabel().getText());
        }
        if (!((ComboBoxValidator) jComboBox3).validarCampo()) {
            fieldList.add(((ComboBoxValidator) jComboBox3).getJLabel().getText());
        }
        return fieldList;
    }

    private int adicionarOrdemServico() {
        try {
            try {
                JanelaLogin.connection.setAutoCommit(false);

                OrdemServicoDao ordemServicoDao = new OrdemServicoDao();
                ordemServicoDao.setTipo(TipoOS.DEMANDA);
                ordemServicoDao.setProblemaInformado(jTextField1.getText());
                ordemServicoDao.setIdPontoAtendimento(PontoAtendimentoDao.buscarIdPontoAtendimentoPorIdentificador(jComboBox2.getSelectedItem().toString()));
                ordemServicoDao.setIdProcedimento(ProcedimentoDao.buscarIdProcedimentoPorNome(jComboBox3.getSelectedItem().toString()));
                ordemServicoDao.setNecessitaAvaliacao(jCheckBox1.isSelected());
                ordemServicoDao.inserir();

                SituacaoOrdemServicoDao situacaoOrdemServicoDao = new SituacaoOrdemServicoDao();
                situacaoOrdemServicoDao.setSituacao(SituacaoOS.EMABERTO);
                situacaoOrdemServicoDao.setIdOrdemServico(ordemServicoDao.getId());
                situacaoOrdemServicoDao.setIdUsuario(JanelaLogin.getUsuario().getId());
                situacaoOrdemServicoDao.setModificacao(DateConverter.getDataAtualBancoDados());
                situacaoOrdemServicoDao.setAtivo(true);
                situacaoOrdemServicoDao.inserir();


                JOptionPane.showMessageDialog(null, "Ordem de Serviço cadastrada com sucesso. OS Nº (" + ordemServicoDao.getId() + ") .", this.getTitle(), JOptionPane.INFORMATION_MESSAGE);
                Object[] options = {"Sim", "Não"};
                int j = JOptionPane.showOptionDialog(null, "Deseja emitir/imprimir a OS Nº (" + ordemServicoDao.getId() + " )?", "Sair", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
                if (j == JOptionPane.YES_OPTION) {
                    this.imprimir(ordemServicoDao.getId());
                }

                JanelaLogin.connection.commit();
                this.dispose();
            } catch (Exception e) {
                JanelaLogin.connection.rollback();
                MensagemExcessao.mostrarMensagem(e, this.getTitle());
            } finally {
                JanelaLogin.connection.setAutoCommit(true);
            }

        } catch (Exception ex) {
            MensagemExcessao.mostrarMensagem(ex, this.getTitle());
        }
        return 0;
    }

    private int editarOrdemServico() {
        try {
            try {
                JanelaLogin.connection.setAutoCommit(false);

                OrdemServicoDao ordemServicoDao = new OrdemServicoDao();
                ordemServicoDao.buscar(idOrdemServico);
                ordemServicoDao.setMaterialUtilizado(jTextArea1.getText());
                ordemServicoDao.setDificuldades(jTextArea2.getText());

                for (int i = 0; i < listaSituacao.size(); i++) {


                    SituacaoOrdemServicoDao situacaoOrdemServicoDao = listaSituacao.get(i);
                    if (situacaoOrdemServicoDao.getId() == 0) {
                        SituacaoOrdemServicoDao ultimaSituacaoOrdemServicoDao = new SituacaoOrdemServicoDao();
                        ultimaSituacaoOrdemServicoDao.buscar(SituacaoOrdemServicoDao.buscarUltimaSituacao(idOrdemServico));
                        ultimaSituacaoOrdemServicoDao.setAtivo(false);
                        ultimaSituacaoOrdemServicoDao.atualizar();

                        situacaoOrdemServicoDao.setIdOrdemServico(ordemServicoDao.getId());
                        situacaoOrdemServicoDao.inserir();

                        if (situacaoOrdemServicoDao.getSituacao() == SituacaoOS.FINALIZADA || situacaoOrdemServicoDao.getSituacao() == SituacaoOS.CANCELADA) {
                            ordemServicoDao.setFinalizada(true);
                        }
                        if (situacaoOrdemServicoDao.getSituacao() == SituacaoOS.EMEXECUSSAO) {
                            ordemServicoDao.setEmitida(true);
                        }
                    }
                }

                ordemServicoDao.atualizar();

                JanelaLogin.connection.commit();

                JOptionPane.showMessageDialog(null, "Ordem de Serviço atualizada com sucesso.", this.getTitle(), JOptionPane.INFORMATION_MESSAGE);
                this.dispose();
            } catch (Exception e) {
                JanelaLogin.connection.rollback();
                MensagemExcessao.mostrarMensagem(e, this.getTitle());
            } finally {
                JanelaLogin.connection.setAutoCommit(true);
            }

        } catch (Exception ex) {
            MensagemExcessao.mostrarMensagem(ex, this.getTitle());
        }
        return 0;
    }

    private void verificarCampoObrigatorios() {
        ((TextFieldValidator) jTextField1).validarCampo();
        ((ComboBoxValidator) jComboBox1).validarCampo();
        ((ComboBoxValidator) jComboBox2).validarCampo();
        ((ComboBoxValidator) jComboBox3).validarCampo();
    }

    public void imprimir(int idOrdemServico) {
        try {
            HashMap parameters = new HashMap();

            OrdemServicoDao ordemServicoDao = new OrdemServicoDao();
            ordemServicoDao.buscar(idOrdemServico);

            SituacaoOrdemServicoDao situacaoOrdemServicoDao = new SituacaoOrdemServicoDao();
            situacaoOrdemServicoDao.buscar(SituacaoOrdemServicoDao.buscarUltimaSituacao(idOrdemServico));

            UsuarioDao usuarioDao = new UsuarioDao();
            usuarioDao.buscar(situacaoOrdemServicoDao.getIdUsuario());


            parameters.put("idOrdemServico", (long) idOrdemServico);
            parameters.put("situacao", EnumSituacaoOrdemServico.ConvertEnumString(situacaoOrdemServicoDao.getSituacao()));
            parameters.put("data", Format.formatTimeStampToCompleteDatetime(situacaoOrdemServicoDao.getModificacao()));
            parameters.put("solicitante", usuarioDao.getNome());
            InputStream is = this.getClass().getClassLoader().getResourceAsStream("manager/modulo/ordemservico/relatorio/OrdemServico.jasper");
            Connection connection = JanelaLogin.getConnection();
            JasperPrint relat = JasperFillManager.fillReport(is, parameters, connection);
            JasperViewer.viewReport(relat, false);

            if (!ordemServicoDao.isEmitida()) {
                ordemServicoDao.setEmitida(true);
                ordemServicoDao.atualizar();

                if (situacaoOrdemServicoDao.getSituacao() == SituacaoOS.EMABERTO) {

                    situacaoOrdemServicoDao.setAtivo(false);
                    situacaoOrdemServicoDao.atualizar();

                    situacaoOrdemServicoDao = new SituacaoOrdemServicoDao();
                    situacaoOrdemServicoDao.setSituacao(SituacaoOS.EMEXECUSSAO);
                    situacaoOrdemServicoDao.setIdOrdemServico(ordemServicoDao.getId());
                    situacaoOrdemServicoDao.setIdUsuario(JanelaLogin.getUsuario().getId());
                    situacaoOrdemServicoDao.setModificacao(DateConverter.getDataAtualBancoDados());
                    situacaoOrdemServicoDao.setAtivo(true);
                    situacaoOrdemServicoDao.inserir();
                }
            }
        } catch (Exception e) {
            MensagemExcessao.mostrarMensagem(e, "Ordem de Serviço");
        }
    }

    private void configurarTabela() {
        tableRender = new TableRender();
        tableModel = new TableModel(getNomeColunasTabelaSituacaoOS(), tableRender, new InterfaceTable() {
            public void tableAction(int id, int columnindex, int rowIndex) {
                if (columnindex < 0) {
                    SituacaoOrdemServicoDao situacaoOrdemServicoDao = listaSituacao.get(rowIndex);

                    jComboBox4.setSelectedItem(EnumSituacaoOrdemServico.ConvertEnumString(situacaoOrdemServicoDao.getSituacao()));
                    jTextArea3.setText(situacaoOrdemServicoDao.getObservacao());

                    UsuarioDao usuarioDao = new UsuarioDao();
                    usuarioDao.buscar(situacaoOrdemServicoDao.getIdUsuario());
                    jTextField6.setText(usuarioDao.getEmail());

                    jButton4.setEnabled(false);
                    jButton5.setEnabled(true);
                }
            }

            public boolean isEditableColumn(int columnIndex) {
                if (columnIndex == 0) {
                    return true;
                }
                return false;
            }
        });
        jTable1.setModel(tableModel);
        jTable1.getColumnModel().getColumn(0).setMaxWidth(20);
        jTable1.getColumnModel().getColumn(0).setMinWidth(20);
        jTable1.getColumnModel().getColumn(0).setResizable(false);
        TableRowComparator tableRowComparator = new TableRowComparator();
        tableRowSorter = tableRowComparator;
        jTable1.setRowSelectionAllowed(false);

        buscarTabela();
    }

    private LinkedList<String> getNomeColunasTabelaSituacaoOS() {
        LinkedList<String> columnNames = new LinkedList<String>();
        columnNames.add("");
        columnNames.add("Modificação");
        columnNames.add("Situação");
        columnNames.add("Usuário");
        return columnNames;
    }

    private void buscarTabela() {
        LinkedList searchResult = new LinkedList();

        LinkedList<Integer> colunaId = new LinkedList<Integer>();
        LinkedList<String> colunaModificao = new LinkedList<String>();
        LinkedList<String> colunaSituacao = new LinkedList<String>();
        LinkedList<String> colunaUsuario = new LinkedList<String>();

        for (int i = 0; i < listaSituacao.size(); i++) {
            SituacaoOrdemServicoDao situacaoOrdemServicoDao = listaSituacao.get(i);
            colunaId.add(situacaoOrdemServicoDao.getId());
            colunaModificao.add(Format.formatTimeStampToCompleteDatetime(situacaoOrdemServicoDao.getModificacao()));
            colunaSituacao.add(EnumSituacaoOrdemServico.ConvertEnumString(situacaoOrdemServicoDao.getSituacao()));
            UsuarioDao usuarioDao = new UsuarioDao();
            usuarioDao.buscar(situacaoOrdemServicoDao.getIdUsuario());
            colunaUsuario.add(usuarioDao.getNome());
        }
        if (listaSituacao.size() > 0) {
            searchResult.add(colunaId);
            searchResult.add(Format.getBooleanLinkedList(colunaId.size()));
            searchResult.add(colunaModificao);
            searchResult.add(colunaSituacao);
            searchResult.add(colunaUsuario);
        }
        tableModel.update(searchResult);
        jTable1.setDefaultRenderer(Object.class, tableRender);
        tableRowSorter.setModel(tableModel);

        jTable1.setRowSorter(tableRowSorter);
    }

    private void limparCadastroSituacao() {
        jComboBox4.setSelectedIndex(0);
        jTextArea3.setText("");
        jTextField6.setText("");
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel3 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        jComboBox1 = new ComboBoxValidator("SELECIONE UMA UNIDADE DE ATENDIMENTO", true, jLabel6);
        jLabel7 = new javax.swing.JLabel();
        jComboBox2 = new ComboBoxValidator("SELECIONE UM PONTO DE ATENDIMENTO", true, jLabel7);
        jLabel9 = new javax.swing.JLabel();
        jTextField1 = new TextFieldValidator(200, -1, true, true, "text", jLabel9);
        jLabel8 = new javax.swing.JLabel();
        jComboBox3 = new ComboBoxValidator("SELECIONE UM PROCEDIMENTO", true, jLabel8);
        jButton2 = new javax.swing.JButton();
        jButton7 = new javax.swing.JButton();
        jCheckBox1 = new javax.swing.JCheckBox();
        jPanel2 = new javax.swing.JPanel();
        jLabel10 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jLabel11 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea2 = new javax.swing.JTextArea();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel12 = new javax.swing.JLabel();
        jComboBox4 = new javax.swing.JComboBox();
        jLabel13 = new javax.swing.JLabel();
        jScrollPane4 = new javax.swing.JScrollPane();
        jTextArea3 = new javax.swing.JTextArea();
        jButton4 = new javax.swing.JButton();
        jLabel14 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();
        jLabel15 = new javax.swing.JLabel();
        jTextField4 = new javax.swing.JTextField();
        jLabel16 = new javax.swing.JLabel();
        jTextField5 = new javax.swing.JTextField();
        jButton5 = new javax.swing.JButton();
        jLabel17 = new javax.swing.JLabel();
        jTextField6 = new javax.swing.JTextField();
        jCheckBox2 = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Ordem de Serviço");
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

        jPanel3.setBackground(Configurations.getBackGroundColor());
        jPanel3.setPreferredSize(new java.awt.Dimension(700, 320));
        jPanel3.setLayout(null);

        jPanel1.setBackground(Configurations.getBackGroundColor());
        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPanel1.setLayout(null);

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel6.setText("Unidade de Atendimento");
        jPanel1.add(jLabel6);
        jLabel6.setBounds(10, 20, 180, 14);

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "SELECIONE UMA UNIDADE DE ATENDIMENTO" }));
        jComboBox1.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jComboBox1ItemStateChanged(evt);
            }
        });
        jPanel1.add(jComboBox1);
        jComboBox1.setBounds(10, 40, 305, 20);

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel7.setText("Ponto de Atendimento");
        jPanel1.add(jLabel7);
        jLabel7.setBounds(320, 20, 180, 14);

        jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "SELECIONE UM PONTO DE ATENDIMENTO" }));
        jPanel1.add(jComboBox2);
        jComboBox2.setBounds(320, 40, 310, 20);

        jLabel9.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel9.setText("Problema Informado");
        jPanel1.add(jLabel9);
        jLabel9.setBounds(10, 120, 180, 14);
        jPanel1.add(jTextField1);
        jTextField1.setBounds(10, 140, 620, 20);

        jLabel8.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel8.setText("Procedimento");
        jPanel1.add(jLabel8);
        jLabel8.setBounds(10, 70, 180, 14);

        jComboBox3.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "SELECIONE UM PROCEDIMENTO" }));
        jPanel1.add(jComboBox3);
        jComboBox3.setBounds(10, 90, 305, 20);

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/add.png"))); // NOI18N
        jButton2.setText("Cadastrar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton2);
        jButton2.setBounds(10, 560, 100, 23);

        jButton7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/cancel.png"))); // NOI18N
        jButton7.setText("Cancelar");
        jButton7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton7ActionPerformed(evt);
            }
        });
        jPanel1.add(jButton7);
        jButton7.setBounds(120, 560, 100, 23);

        jCheckBox1.setBackground(Configurations.getBackGroundColor());
        jCheckBox1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jCheckBox1.setSelected(true);
        jCheckBox1.setText("Necessita de Avaliação");
        jCheckBox1.setEnabled(false);
        jPanel1.add(jCheckBox1);
        jCheckBox1.setBounds(410, 70, 160, 23);

        jPanel2.setBackground(Configurations.getBackGroundColor());
        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Dados da Ordem de Serviço"));
        jPanel2.setLayout(null);

        jLabel10.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel10.setText("Material Utilizado");
        jPanel2.add(jLabel10);
        jLabel10.setBounds(10, 20, 180, 14);

        jTextArea1.setColumns(20);
        jTextArea1.setFont(new java.awt.Font("Monospaced", 1, 10)); // NOI18N
        jTextArea1.setLineWrap(true);
        jTextArea1.setRows(2);
        jTextArea1.setWrapStyleWord(true);
        jScrollPane1.setViewportView(jTextArea1);
        jTextArea1.setDocument(new FixedLengthDocument(300));

        jPanel2.add(jScrollPane1);
        jScrollPane1.setBounds(10, 40, 600, 50);

        jLabel11.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel11.setText("Dificuldades Encontradas");
        jPanel2.add(jLabel11);
        jLabel11.setBounds(10, 100, 180, 14);

        jTextArea2.setColumns(20);
        jTextArea2.setFont(new java.awt.Font("Monospaced", 1, 10)); // NOI18N
        jTextArea2.setLineWrap(true);
        jTextArea2.setRows(2);
        jTextArea2.setWrapStyleWord(true);
        jScrollPane2.setViewportView(jTextArea2);
        jTextArea2.setDocument(new FixedLengthDocument(200));

        jPanel2.add(jScrollPane2);
        jScrollPane2.setBounds(10, 120, 600, 50);

        jPanel1.add(jPanel2);
        jPanel2.setBounds(10, 170, 620, 180);

        jPanel4.setBackground(Configurations.getBackGroundColor());
        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Situação da OS"));
        jPanel4.setLayout(null);

        jScrollPane3.setViewportView(jTable1);

        jPanel4.add(jScrollPane3);
        jScrollPane3.setBounds(320, 60, 290, 130);

        jLabel12.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel12.setText("Nova Situação");
        jPanel4.add(jLabel12);
        jLabel12.setBounds(10, 55, 100, 14);

        jPanel4.add(jComboBox4);
        jComboBox4.setBounds(10, 70, 260, 20);

        jLabel13.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel13.setText("Observações");
        jPanel4.add(jLabel13);
        jLabel13.setBounds(10, 135, 100, 14);

        jTextArea3.setColumns(20);
        jTextArea3.setFont(new java.awt.Font("Monospaced", 1, 10)); // NOI18N
        jTextArea3.setLineWrap(true);
        jTextArea3.setRows(2);
        jTextArea3.setWrapStyleWord(true);
        jScrollPane4.setViewportView(jTextArea3);
        jTextArea3.setDocument(new FixedLengthDocument(200));

        jPanel4.add(jScrollPane4);
        jScrollPane4.setBounds(10, 150, 260, 40);

        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/add.png"))); // NOI18N
        jButton4.setToolTipText("Adicionar");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        jPanel4.add(jButton4);
        jButton4.setBounds(280, 70, 30, 30);

        jLabel14.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel14.setText("Usuário");
        jPanel4.add(jLabel14);
        jLabel14.setBounds(300, 15, 90, 14);

        jTextField3.setDisabledTextColor(new java.awt.Color(0, 0, 0));
        jTextField3.setEnabled(false);
        jPanel4.add(jTextField3);
        jTextField3.setBounds(10, 30, 110, 20);

        jLabel15.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel15.setText("Ultima Modificação ");
        jPanel4.add(jLabel15);
        jLabel15.setBounds(10, 15, 120, 14);

        jTextField4.setDisabledTextColor(new java.awt.Color(0, 0, 0));
        jTextField4.setEnabled(false);
        jPanel4.add(jTextField4);
        jTextField4.setBounds(300, 30, 310, 20);

        jLabel16.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel16.setText("Situação Atual ");
        jPanel4.add(jLabel16);
        jLabel16.setBounds(125, 15, 100, 14);

        jTextField5.setDisabledTextColor(new java.awt.Color(0, 0, 0));
        jTextField5.setEnabled(false);
        jPanel4.add(jTextField5);
        jTextField5.setBounds(125, 30, 170, 20);

        jButton5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/manager/images/cancel.png"))); // NOI18N
        jButton5.setToolTipText("Cancelar");
        jButton5.setEnabled(false);
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });
        jPanel4.add(jButton5);
        jButton5.setBounds(280, 120, 30, 30);

        jLabel17.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel17.setText("Usuário");
        jPanel4.add(jLabel17);
        jLabel17.setBounds(10, 95, 90, 14);

        jTextField6.setDisabledTextColor(new java.awt.Color(0, 0, 0));
        jTextField6.setEnabled(false);
        jPanel4.add(jTextField6);
        jTextField6.setBounds(10, 110, 260, 20);

        jPanel1.add(jPanel4);
        jPanel4.setBounds(10, 360, 620, 200);

        jCheckBox2.setBackground(Configurations.getBackGroundColor());
        jCheckBox2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jCheckBox2.setText("AVALIADA");
        jCheckBox2.setEnabled(false);
        jPanel1.add(jCheckBox2);
        jCheckBox2.setBounds(440, 100, 90, 23);

        jPanel3.add(jPanel1);
        jPanel1.setBounds(0, 0, 640, 590);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 639, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 589, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        LinkedList<String> listaValidacao = validarCamposOrdemServico();
        if (listaValidacao.size() == 0) {
            if (idOrdemServico == 0) {
                adicionarOrdemServico();
            } else {
                editarOrdemServico();
            }
        } else {
            JOptionPane.showMessageDialog(null, ValidationFunctions.getValidationMessage(listaValidacao), this.getTitle(), JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButton7ActionPerformed

    private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBox1ItemStateChanged
        try {
            if (jComboBox1.getItemCount() > 0) {
                String itemSelecionado = jComboBox1.getSelectedItem().toString();
                jComboBox2.removeAllItems();
                jComboBox2.addItem("SELECIONE UM PONTO DE ATENDIMENTO");
                if (!itemSelecionado.equalsIgnoreCase("SELECIONE UMA UNIDADE DE ATENDIMENTO")) {
                    LinkedList<String> listaPontoAtendimento = (new PontoAtendimentoDao()).buscar("Identificador do Ponto Atend.", "%", false);
                    for (int i = 0; i < listaPontoAtendimento.size(); i++) {
                        jComboBox2.addItem(listaPontoAtendimento.get(i));
                    }
                }
            }
        } catch (Exception e) {
            MensagemExcessao.mostrarMensagem(e, "Ordem de Serviço");
        }
    }//GEN-LAST:event_jComboBox1ItemStateChanged

    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        WindowsFunctions.resizePanel(jPanel3, jPanel1);
    }//GEN-LAST:event_formComponentResized

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        SituacaoOS situacaoOS = EnumSituacaoOrdemServico.ConvertStringEnum(jComboBox4.getSelectedItem().toString());
        if (situacaoOS != SituacaoOS.NAOENCONTRADO) {
            Object[] options = {"Sim", "Não"};
            int j = JOptionPane.showOptionDialog(null, "Confirmar cadastro de nova situação?", "Sair", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
            if (j == JOptionPane.YES_OPTION) {
                SituacaoOrdemServicoDao situacaoOrdemServicoDao = new SituacaoOrdemServicoDao();
                situacaoOrdemServicoDao.setSituacao(situacaoOS);
                situacaoOrdemServicoDao.setObservacao(jTextArea3.getText());
                situacaoOrdemServicoDao.setIdUsuario(JanelaLogin.getUsuario().getId());
                situacaoOrdemServicoDao.setModificacao(DateConverter.getDataAtualBancoDados());
                situacaoOrdemServicoDao.setAtivo(true);

                listaSituacao.add(situacaoOrdemServicoDao);
                buscarTabela();
                limparCadastroSituacao();
            }
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        jButton5.setEnabled(false);
        jButton4.setEnabled(true);
        limparCadastroSituacao();
    }//GEN-LAST:event_jButton5ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton7;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JCheckBox jCheckBox2;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBox2;
    private javax.swing.JComboBox jComboBox3;
    private javax.swing.JComboBox jComboBox4;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextArea jTextArea2;
    private javax.swing.JTextArea jTextArea3;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField jTextField6;
    // End of variables declaration//GEN-END:variables
}
